﻿using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Warehouse.Domain;
using Warehouse.Domain.DTO;
using Warehouse.Infrstructre.Interface;
using Warehouse.Read.API.Applcation.Command.StorehouseCommand;
using Warehouse.Read.API.Dtos;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;

namespace Warehouse.Read.API.Controllers
{
    /// <summary>
    /// 库位控制器(读)
    /// </summary>
    [Route("api/[controller]/[action]")]
    [Authorize]
    [ApiController]
   
    public class ReadStorehouseController : ControllerBase
    {

        private readonly IMediator mediator;
        private readonly IStorehouseRepository _store;
        ILogger<ReadStorehouseController> _logger;

        public ReadStorehouseController(IMediator mediator, IStorehouseRepository store, ILogger<ReadStorehouseController> logger)
        {
            this.mediator = mediator;
            _store = store;
            _logger = logger;
        }


        /// <summary>
        /// 分页显示
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Dtos.ApiResult<PageDTO<StoreWareDTO>>> GetStorehouseList([FromQuery]SelectStorehouseCommannd command)
        {
            Dtos.ApiResult<PageDTO<StoreWareDTO>> result = new Dtos.ApiResult<PageDTO<StoreWareDTO>>();

            try
            {
                var uid = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;//获取用户id
                var sid = HttpContext.User.FindFirst(JwtRegisteredClaimNames.Sid)?.Value;//获取公司id
                command.Uid = Convert.ToInt32(uid);
                command.Oid = sid;
                result.Data = await mediator.Send(command);
            }
            catch (Exception ex)
            {

                result.Code = -1;
                result.Message = ex.Message;
                _logger.LogError(ex, ex.Message);
                throw;
            }
            return result;
        }

        /// <summary>
        /// 反填
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Dtos.ApiResult<StoreHouse>>  GetStorehouseInfo([FromQuery]FillStorehouseCommand command)
        {
            Dtos.ApiResult<StoreHouse> result = new Dtos.ApiResult<StoreHouse>();

            try
            {
             
                result.Data = await mediator.Send(command);
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }

        /// <summary>
        /// 库位下仓库列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<Dtos.ApiResult<List<Warehouseinfo>>> GetWarelist()
        {
            Dtos.ApiResult<List<Warehouseinfo>> result = new Dtos.ApiResult<List<Warehouseinfo>>();

            try
            {
                result.Data = await mediator.Send(new SelectWareListCommand());
            }
            catch (Exception ex)
            {
                result.Code = -1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }


        /// <summary>
        /// //导出excel
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ExportExcelStore([FromQuery]SelectStorehouseCommannd command)
        {

            var list = await mediator.Send(command);

            IWorkbook wb = new XSSFWorkbook();
            ISheet sheet = wb.CreateSheet("库位信息");

            IRow row = sheet.CreateRow(0);
            row.CreateCell(0).SetCellValue("库位编号");
            row.CreateCell(1).SetCellValue("库位名称");
            row.CreateCell(2).SetCellValue("库位类型");
            row.CreateCell(3).SetCellValue("所属仓库");
            row.CreateCell(4).SetCellValue("备注");
            row.CreateCell(5).SetCellValue("创建人");
            row.CreateCell(6).SetCellValue("创建时间");

            int i = 1;
            foreach (var item in list.list)
            {
                row = sheet.CreateRow(i);
                row.CreateCell(0).SetCellValue(item.StorehouseCode);
                row.CreateCell(1).SetCellValue(item.StorehouseName);
                row.CreateCell(2).SetCellValue(item.StorehouseType);
                row.CreateCell(3).SetCellValue(item.WarehouseName);
                row.CreateCell(4).SetCellValue(item.Sremark);
                row.CreateCell(5).SetCellValue(item.AddName);
                row.CreateCell(6).SetCellValue(item.AddTime.ToString());
                i++;
            }

            byte[] bytes;


            using (MemoryStream ms = new MemoryStream())
            {
                wb.Write(ms);
                bytes = ms.ToArray();
            }

            string mapPath = new FileExtensionContentTypeProvider().Mappings[".xlsx"];
            return File(bytes, mapPath, "库位信息.xlsx");

        }




    }
}
